package com.gyl.example.handler;


import com.gyl.common.bean.AjaxResult;
import com.gyl.common.bean.exception.BusinessException;
import com.gyl.common.utils.ExceptionUtil;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Optional;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

/**
 * 全局异常处理器
 *
 * @author gyl
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Log log = LogFactory.get();

    /**
     * 最大的异常捕捉
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e) {
        log.error(ExceptionUtil.printStackTrace(e));
        log.error(e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 捕捉业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public AjaxResult handleBusinessException(BusinessException e) {
        log.error("{}:{}", e.getCode(), e.getErrorMsg());
        return AjaxResult.error(e.getCode(), Optional.ofNullable(e.getErrorMsg()).orElse(e.getMessage()));
    }

}
